import { Post } from './request'

export const getUnionId = (cb:(id:string)=>void) => {
  wx.login({
    success: res => {
      console.log(res.code)
      // 发送 res.code 到后台换取 openId, sessionKey, unionId
      unionidService(res.code, (id: string) => {
        if (cb) {
          cb(id)
        }
      })
    },
  })
}

const unionidService = (code:string, onSuccess:(id:string) => void)=> {
  Post({
    url: "https://svs.tinyorbits.com/inference/api/wx/js_session",
    data: {
      "code": code
    }
  }).then((res: any) => {
    console.log(res.data)
    let unionid = res.data.unionid
    onSuccess(unionid)
  }, (err: any) => {
    console.log(err.errMsg)
  })
}

export const bindPhone = (code:string, unionid:string, cb:(uid:string)=>void) => {
  Post({
    url:'https://svs.tinyorbits.com/inference/api/wx/bind_phone_number',
    data: {
      "code": code,
      "unionId": unionid
    }
  }).then((res:any)=> {
    console.log(res.data)
    let success = res.data.code == '200'
    if (!success) {
      cb("")
      return
    }
    cb(res.data.message)

  }).catch((err:any)=> {
    cb("")
  })
}

export const restoreAuth = (data:any) => {
  console.log('恢复缓存数据')
  data.uid = wx.getStorageSync('uid')
  data.unionid = wx.getStorageSync('unionid')
  data.token = wx.getStorageSync('token')
  data.expiredAt = wx.getStorageSync('expiredAt')
  console.log(data)
}

export const checkLogin = (data:any):boolean => {
  console.log('检查登录状态')
  let expiredAt = data.expiredAt
  if (!expiredAt) {
    expiredAt = 0;
  }
  let now = new Date().getTime()
  if (now > expiredAt) { // 检查是否过期了
    console.log('登录状态过期')
    return false
  }
  if (!data.uid) { // 检查是否保存了uid
    console.log('无uid')
    return false;
  }
  if (!data.token) { // 检查是否保存了uid
    console.log('无token')
    return false;
  }
  return true;
}